package com.cqhfan.chatroom.mq;

import com.cqhfan.chatroom.domain.dto.WebSocketMessageDTO;
import com.cqhfan.chatroom.domain.po.ChatMessage;
import com.cqhfan.chatroom.service.IChatGroupUserService;
import com.cqhfan.chatroom.service.IChatMessageService;
import com.cqhfan.common.constants.MqConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author 眭传洪
 * @create 2024-11-20 17:08
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ChatMessageListener {

    private final IChatMessageService chatMessageService;

    private final IChatGroupUserService chatGroupUserService;

    @Value("${server.port}")
    private String port;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConstants.ExChange.CHAT_EXCHANGE, type = ExchangeTypes.TOPIC),
            value = @Queue(value = MqConstants.Queue.CHAT_MSG_SAVE_QUEUE + ".#{@environment.getProperty('server.port')}"),
            key = MqConstants.key.SAVE_TO_DB + ".#{@environment.getProperty('server.port')}"
    ))
    public void listenChatMessageSave(String msg) {
        log.info("mq接收到聊天消息保存的数据，port={}, msg={}", port, msg);
        chatMessageService.saveChatMessage(msg);
    }

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConstants.ExChange.CHAT_CREATE_GROUP_EXCHANGE, type = ExchangeTypes.FANOUT),
            value = @Queue(value = MqConstants.Queue.CREATE_GROUP_NOTICE_QUEUE + ".#{@environment.getProperty('server.port')}")
    ))
    public void listenChatGroupCreate(String msg) {
        log.info("mq接收到创建群聊的消息，port={}, msg = {}", port, msg);
        chatGroupUserService.noticeChatGroupCreateMsg(msg);
    }

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConstants.ExChange.CHAT_SEND_EXCHANGE, type = ExchangeTypes.FANOUT),
            value = @Queue(value = MqConstants.Queue.CHAT_MSG_SEND_QUEUE + ".#{@environment.getProperty('server.port')}")
    ))
    public void listenSendMsg(String msg) {
        log.info("mq接收到聊天消息的数据：port={}, msg = {}", port, msg);
        chatMessageService.listenSendMsg(msg);
    }

}
